package welsir.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import welsir.entity.dos.User;
import welsir.entity.dos.UserRole;
import welsir.entity.vo.ResultMessage;
import welsir.mapper.UserRoleMapper;
import welsir.security.AuthUser;
import welsir.security.annotations.Authentication;
import welsir.security.enums.UserEnums;
import welsir.service.IUserService;
import welsir.util.ResultUtil;
import welsir.util.RoleAuthUtil;
import welsir.util.TokenUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author welsir
 * @date 2023/3/3 20:52
 */
@RestController
@RequestMapping("/user")
@Validated
@Api(value = "用户Controller",tags = {"用户中心接口"})
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RoleAuthUtil roleAuthUtil;
    /**
     * 用户名登录
     * @return 登录token
     */
    @ApiOperation(value = "用户名密码登录")
    @PostMapping("/userLogin")
    public ResultMessage<Object> userLogin(@RequestBody User user) {
        return ResultUtil.data(this.userService.usernameLogin(user.getUsername(), user.getPassword()));
    }

    /**
     * @description:  查询所有用户信息
     * @param: []
     * @return: []
     * @author: WELSIR
     */
    @ApiOperation(value = "查询所有用户")
    @GetMapping("queryAllUser")
    public ResultMessage<List<User>> queryAllUserInfo() {
        return ResultUtil.data(userService.queryAllUser());
    }

    /**
     * @description:  根据id查用户信息
     * @param: [id]
     * @return: [id]
     * @author: WELSIR
     */
    @ApiOperation(value = "根据用户uid查询用户")
    @GetMapping("queryUserById/{id}")
    public ResultMessage<User> queryUserByUid(@Validated
                                              @PathVariable Long id) {
        return ResultUtil.data(userService.queryUserByUid(id));
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("updateUser")
    public ResultMessage<Integer> updateUser(@Validated
                                                 @RequestBody User user) {
        return ResultUtil.data(userService.updateUserByUser(user));
    }

    @ApiOperation(value = "根据uid删除用户")
    @GetMapping("deleteUserById/{id}")
    public ResultMessage<Integer> deleteUserByUid(@Validated
                                                  @PathVariable Long id) {
        if (userService.deleteUserByUid(id)==1) {
            return ResultUtil.success();
        }else{
            return ResultUtil.error(500,"用户不存在或者出现某些问题");
        }

    }

    @ApiOperation(value = "用户注册")
    @PostMapping("register")
    public ResultMessage<Object> registerUser(@RequestBody @Validated
                                                     User user) {
        user.setNickname(user.getUsername());
        return ResultUtil.data(userService.registerUser(user));
    }

    @ApiOperation(value = "分页查询用户")
    @GetMapping("queryUserPage/{page}/{size}")
    public ResultMessage<Page<User>> queryUserPage(@Validated
                                                   @PathVariable int page,
                                                   @Validated
                                                   @PathVariable int size) {
        return ResultUtil.data(userService.queryUserPage(size, page));
    }

    @ApiOperation(value = "分页查询用户权限")
    @PostMapping("checkAdmin")
    public ResultMessage<Object> checkAdmin() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        AuthUser authUser = tokenUtil.parseToken(token);
        if(authUser==null){
            return ResultUtil.error(403,"token失效");
        }
        return ResultUtil.data(roleAuthUtil.getUserRole(authUser.getId()));
    }

    @ApiOperation(value = "获取管理员信息")
    @GetMapping("getAdmin")
    public ResultMessage<List<User>> getAdmin(){
        List<UserRole> roles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("role_id", UserEnums.ADMIN.getRole()));
        List<User> users = new ArrayList<>();
        for (UserRole role : roles) {
            User user = userService.queryUserByUid(Long.valueOf(role.getUserId()));
            if (!Objects.isNull(user)) {
                users.add(user);
            }

        }
        return ResultUtil.data(users);
    }

    @ApiOperation(value = "获取非管理员信息")
    @GetMapping("getUnAdmin")
    public ResultMessage<List<User>> getUnAdmin(){
        List<UserRole> roles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("role_id", UserEnums.USER.getRole()));
        List<User> users = new ArrayList<>();
        for (UserRole role : roles) {
            User user = userService.queryUserByUid(Long.valueOf(role.getUserId()));
            if (!Objects.isNull(user)) {
                users.add(user);
            }
        }
        return ResultUtil.data(users);
    }

    //添加管理员
    @Authentication(role = UserEnums.ADMIN)
    @ApiOperation(value = "更改权限管理员")
    @PostMapping("changeRole")
    public ResultMessage<Integer> changeRole(@RequestBody JSONObject jsonObject){
        Integer uid = (Integer) jsonObject.get("uid");
        Integer roleId = (Integer) jsonObject.get("roleId");
        if(roleId>UserEnums.values().length){
            return ResultUtil.error(500,"权限不存在");
        }
        return ResultUtil.data(userRoleMapper.update(new UserRole(uid,roleId),new QueryWrapper<UserRole>().eq("user_id",uid)));
    }

    @ApiOperation(value = "获取用户安全信息")
    @GetMapping("userInfo")
    public ResultMessage<User> userInfo(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        AuthUser authUser = tokenUtil.parseToken(token);
        if(authUser==null){
            return ResultUtil.error(403,"token失效");
        }
        return ResultUtil.data(userService.queryUserByUid(authUser.getId().longValue()));
    }

    @ApiOperation(value = "获得用户数量")
    @GetMapping("getUserCount")
    public ResultMessage<Integer> getUserCount(){
        return ResultUtil.data(userService.count());
    }

    @ApiOperation(value = "更改密码")
    @PostMapping("changePassword")
    public ResultMessage<Integer> changePassword(@RequestBody JSONObject jsonObject){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        AuthUser authUser = tokenUtil.parseToken(token);
        if(authUser==null){
            return ResultUtil.error(403,"token失效");
        }
        String oldPassword = jsonObject.getString("oldPassword");
        String newPassword = jsonObject.getString("newPassword");
        User user = userService.queryUserByUid(authUser.getId().longValue());
        if(Objects.isNull(user)){
            return ResultUtil.error(500,"用户不存在");
        }
        if (!user.getPassword().equals(oldPassword)) {
            return ResultUtil.error(500,"原密码错误");
        }
        user.setPassword(newPassword);
        return ResultUtil.data(userService.updateUserByUser(user));
    }

}
